package com.west_traveler.ximalayafm;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.west_traveler.application.BaseApplication;
import com.west_traveler.entity.TempDS;
import com.west_traveler.entity.TempList;
import com.west_traveler.play_service.PlayService;
import com.west_traveler.utils.CommonUtils;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class PlayActivity extends AppCompatActivity implements View.OnClickListener, PopupWindow.OnDismissListener {

    private ImageView ivPlay;
    private Intent serviceIntent;
    private ImageView ivAuthorIcon;
    private TextView tvAuthorNickname;
    private TextView tvTitle;
    private ImageView ivLargeImage;
    private SeekBar seekBar;
    private TextView tvCurTime;
    private TextView tvTotalProgress;
    private LocalBroadcastManager manager;
    private boolean updateProFlg = true;//用于屏蔽拖拽seekbar时的闪烁问题
    private BroadcastReceiver receiver;
    private boolean startService;
    private PlayService playService;
    private PlayServiceConnection connection;
    private int curProgress;
    private ImageView ivPrevious;
    private ImageView ivNext;
    private int index;
    private String[] allPlaySources;
    private String curUrl;
    private TempDS ds;
    private ImageView ivBuffer;
    private Animator animator;
    private ImageView ivMore;
    private PopupWindow window;
    private WindowManager.LayoutParams layoutParams;
    private PopupWindow timerOffWindow;
    private ImageView ivTimerOff;
    private WindowManager.LayoutParams timerOffLP;
    private Timer timerOff;
    private int totalProgress;
    private int currentProgress;

    private Handler handler;
    private int timerOffTime;
    private TextView tvTimeOffCurTime;
    private TextView tvPlayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);

        initView();

        setDataToWidget();

        aboutService();

        playerOptions();

        aboutReceiver();

        aboutSeekBar();


    }

//    public void showVersion(View view){
//        try {
//            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//            int versionCode = packageInfo.versionCode;
//            tvPlayList.setText(versionCode+"");
//            Toast.makeText(this, packageInfo.versionName, Toast.LENGTH_SHORT).show();
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//
//    }

    private void aboutService() {

        serviceIntent = new Intent(getApplicationContext(), PlayService.class);
        serviceIntent.putExtra("playUrlArrays", allPlaySources);
        serviceIntent.putExtra("index", index);

        if (startService && !BaseApplication.lastUrl.equals(curUrl)) {

            if (BaseApplication.serviceRunning) {
                stopService(serviceIntent);
            }

            startService(serviceIntent);

            BaseApplication.lastUrl = curUrl;
            BaseApplication.serviceRunning = true;
        }


        connection = new PlayServiceConnection();
        bindService(serviceIntent, connection, BIND_AUTO_CREATE);


    }

    private void playerOptions() {

        animator = AnimatorInflater.loadAnimator(this, R.animator.player_buffer);
        animator.setTarget(ivBuffer);
        animator.start();


        ivPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playService.play();

            }
        });

        ivPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playService.previous();
                int previousIndex = --index;
                if (previousIndex >= 0) {
                    setInfo(previousIndex);
                    ivPrevious.setEnabled(true);
                    ivNext.setEnabled(true);
                    if (previousIndex == 0) {
                        ivPrevious.setEnabled(false);
                    }
                }else if(previousIndex == 1){
                    ivPrevious.setEnabled(false);
                }
//                else {
//                    ivPrevious.setEnabled(false);
//                    index = 0;
//                }
            }
        });

        ivNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                next();
            }
        });

        aboutPopupWindow();

        aboutTimerOff();

    }

    private void next() {
        playService.next();
        int nextIndex = ++index;
        if (nextIndex < allPlaySources.length) {
            setInfo(nextIndex);
            ivNext.setEnabled(true);
            ivPrevious.setEnabled(true);
            if (nextIndex == allPlaySources.length - 1) {
                ivNext.setEnabled(false);
            }
        }else if(nextIndex == allPlaySources.length-2){
            ivNext.setEnabled(false);
        }
//        else {
//            index = allPlaySources.length - 1;
//        }
    }

    private void aboutTimerOff() {
        View view = View.inflate(this, R.layout.popup_window_timer_off, null);
        timerOffWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
        timerOffWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));
        timerOffWindow.setFocusable(true);
        timerOffWindow.setAnimationStyle(R.style.popupWindowAnimStyle);
        timerOffLP = getWindow().getAttributes();

        ivTimerOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timerOffWindow.showAtLocation(ivTimerOff, Gravity.BOTTOM | Gravity
                        .CENTER_HORIZONTAL, 0, 0);
                timerOffLP.alpha = 0.5f;
                getWindow().setAttributes(layoutParams);

            }
        });

        view.findViewById(R.id.btn_player_timer_off_close_id).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timerOffWindow.dismiss();
            }
        });

        timerOffWindow.setOnDismissListener(this);

        ListView lvTimerOff = (ListView) view.findViewById(R.id.lv_timer_off_id);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (timerOffTime > 0) {
                    timerOffTime -= 1000;
                    tvTimeOffCurTime.setText(CommonUtils.parseTime(timerOffTime));

                }

                if (timerOffTime == 0) {
                    playService.play();
                    if (timerOff != null) {
                        timerOff.cancel();
                        timerOff.purge();
                        timerOff = null;
                    }
                }
            }
        };

        lvTimerOff.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                timerOffTime = 0;
                switch (i) {
                    case 1:
                        timerOffTime = totalProgress - currentProgress;
                        break;
                    case 2:
                        timerOffTime = 600000;
                        break;
                    case 3:
                        timerOffTime = 1200000;
                        break;
                    case 4:
                        timerOffTime = 1800000;
                        break;
                    case 5:
                        timerOffTime = 3600000;
                        break;
                    case 6:
                        timerOffTime = 5400000;
                        break;
                    default:
                        break;
                }
                if (timerOff != null) {
                    timerOff.cancel();
                    timerOff.purge();
                    timerOff = null;
                }
                timerOff = new Timer();
                timerOff.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (timerOffTime > 0) {
                            handler.sendEmptyMessage(0);
                        }
                    }
                }, 0, 1000);

                timerOffWindow.dismiss();
            }
        });

    }

    private void aboutPopupWindow() {
        View inflate = View.inflate(this, R.layout.popup_window_more_menu, null);
        window = new PopupWindow(inflate, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));
        window.setFocusable(true);
        layoutParams = getWindow().getAttributes();

        ivMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.showAtLocation(ivMore, Gravity.BOTTOM | Gravity
                        .CENTER_HORIZONTAL, 0, 0);
                layoutParams.alpha = 0.5f;
                getWindow().setAttributes(layoutParams);
            }
        });


        inflate.findViewById(R.id.btn_dismiss_popup_window_id).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });

        window.setAnimationStyle(R.style.popupWindowAnimStyle);

        window.setOnDismissListener(this);

        LinearLayout llTop = (LinearLayout) inflate.findViewById(R.id.ll_more_top_toolbar_id);
        LinearLayout llBottom = (LinearLayout) inflate.findViewById(R.id.ll_more_bottom_toolbar_id);

        for (int i = 0; i < llTop.getChildCount(); i++) {
            llTop.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(PlayActivity.this, ((TextView) (((LinearLayout) view).getChildAt(1))).getText(), Toast.LENGTH_SHORT).show();
                    window.dismiss();
                }
            });

            llBottom.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(PlayActivity.this, ((TextView) (((LinearLayout) view).getChildAt(1))).getText(), Toast.LENGTH_SHORT).show();
                    window.dismiss();
                }
            });

        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                window.dismiss();
                onBackPressed();
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDismiss() {
        layoutParams.alpha = 1;
        getWindow().setAttributes(layoutParams);
    }

    private class PlayServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            PlayService.PlayBinder binder = (PlayService.PlayBinder) iBinder;
            playService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //stopService(serviceIntent);
        }
    }

    private void setDataToWidget() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("playDataSource");
        ds = bundle.getParcelable("ds");
        index = intent.getIntExtra("index", -1);
        allPlaySources = bundle.getStringArray("allPlaySource");
        startService = bundle.getBoolean("startService", false);

        curUrl = allPlaySources[index];
        setInfo(index);

    }

    private void setInfo(int index) {
        TempList tempList = ds.getList().get(index);
        tvAuthorNickname.setText(tempList.getNickName());
        tvTitle.setText(tempList.getTitle());
        Picasso.with(this).load(ds.getSmallLogo()).into(ivAuthorIcon);
        Picasso.with(this).load(tempList.getCoverLarge()).into(ivLargeImage);
    }

    private void initView() {
        ivPlay = (ImageView) findViewById(R.id.iv_player_play_id);
        ivPrevious = (ImageView) findViewById(R.id.iv_player_previous_id);
        ivNext = (ImageView) findViewById(R.id.iv_player_next_id);
        ivAuthorIcon = (ImageView) findViewById(R.id.iv_author_small_icon_id);
        tvAuthorNickname = (TextView) findViewById(R.id.tv_author_nickname_id);
        tvTitle = (TextView) findViewById(R.id.tv_player_title_id);
        ivLargeImage = (ImageView) findViewById(R.id.iv_play_content_image_id);
        seekBar = (SeekBar) findViewById(R.id.sb_player_toolbar_progress_id);
        tvCurTime = (TextView) findViewById(R.id.tv_player_current_time_id);
        tvTotalProgress = (TextView) findViewById(R.id.tv_player_total_time_id);
        findViewById(R.id.iv_back_id).setOnClickListener(this);
        ivBuffer = (ImageView) findViewById(R.id.iv_player_buffer_id);
        ivMore = (ImageView) findViewById(R.id.iv_more_toolbar_id);
        ivTimerOff = ((ImageView) findViewById(R.id.iv_player_time_off_id));
        tvTimeOffCurTime = (TextView) findViewById(R.id.tv_timer_off_time_id);
        tvPlayList = (TextView) findViewById(R.id.tv_play_list_id);

    }

    private void aboutReceiver() {
        manager = LocalBroadcastManager.getInstance(getApplicationContext());
        receiver = new PlayerProgressReceiver();
        IntentFilter filter = new IntentFilter("ximalaya.fm.progress");
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        manager.registerReceiver(receiver, filter);
    }

    private void aboutSeekBar() {


        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

                tvCurTime.setText(CommonUtils.parseTime(i));

                if (b) {
                    curProgress = i;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                updateProFlg = false;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                playService.setCurrentTime(curProgress);
                updateProFlg = true;
            }
        });

    }

    private class PlayerProgressReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if ("ximalaya.fm.progress".equals(intent.getAction())) {
                //总时长
                totalProgress = intent.getIntExtra("totalProgress", -1);
                if (totalProgress > 0) {
                    seekBar.setMax(totalProgress);
                    tvTotalProgress.setText(CommonUtils.parseTime(totalProgress));
                }

                //播放
                currentProgress = intent.getIntExtra("currentProgress", -1);
                if (currentProgress > 0) {
                    if (updateProFlg) {
                        seekBar.setProgress(currentProgress);
                    }

                }

                //缓冲
                int bufferProgress = intent.getIntExtra("bufferProgress", -1);
                if (bufferProgress > 0) {
                    float curBuffer = ((float) bufferProgress) / 100 * totalProgress;
                    seekBar.setSecondaryProgress((int) curBuffer);
                }

                boolean isPlaying = intent.getBooleanExtra("isPlaying", false);
                //按钮
                if (isPlaying) {
                    animator.cancel();
                    ivBuffer.setVisibility(View.INVISIBLE);
                    ivPlay.setImageResource(R.drawable.selector_player_toolbar_pause_icon);

                } else {
                    ivPlay.setImageResource(R.drawable.selector_player_toolbar_play_icon);
                }

                if (intent.getBooleanExtra("isCompletion", false)) {//自动下一首
                    next();
                }

            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.unregisterReceiver(receiver);
        unbindService(connection);
    }


    @Override
    public void onClick(View view) {
        finish();
        overridePendingTransition(android.R.anim.fade_in, R.anim.down_out);
    }
}
